import os
import sqlite3
from server.config import pkgm_config
from server.database import db_manager
from server.util import en_password, check_password

app_sql_dir = str(os.path.dirname(os.path.abspath(__file__))).replace("\\", "/") + "/schema"


def init_db():
    """init db"""
    print(u"初始化数据库")
    for item in os.listdir(app_sql_dir):
        if item.endswith(".sql"):
            with open(f"{app_sql_dir}/{item}", "r", encoding="utf-8") as f:
                sql_script = f.read()
            conn = sqlite3.connect(pkgm_config.sqlite_db_path)
            cursor = conn.cursor()
            cursor.executescript(sql_script)
            conn.commit()
            conn.close()
    print(u"数据库初始化完成")


async def init_admin_user():
    """init admin user"""
    admin_user = await db_manager.fetch_one("select id,password from user where username=?", (pkgm_config.user_name,))
    if not admin_user:
        await db_manager.insert("user", {"username": pkgm_config.user_name, 
                                         "password": en_password(pkgm_config.user_password), 
                                         "status": 1})
        return
    if not check_password(pkgm_config.user_password, admin_user["password"]):
        await db_manager.update("user", {"password": en_password(pkgm_config.user_password)}, "id=?", (admin_user["id"],))
    print(u"初始化管理员用户完成")


async def init_setting():
    """初始化全局设置"""
    setting_data = [
        {"name": "local_packages_path", "value": "{local_packages_path}/pkgm/packages", "value_type": "path"},
        {"name": "project_path", "value": "{project_path}/pkgm/project", "value_type": "path"},
        {"name": "server_cache_path", "value": "{server_cache_path}/pkgm/cache", "value_type": "path"},
        {"name": "install_path", "value": "{install_path}/pkgm/software", "value_type": "path"},
        {"name": "cache_expiration_time", "value": "300", "value_type": "int"},
        {"name": "pip_url", "value": "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/", "value_type": "http"},
        {"name": "npm_url", "value": "https://nodejs.org/dist/", "value_type": "http"},
        {"name": "package_type", "value": "pip,npm", "value_type": "list"}
        ]
    exists_data = await db_manager.fetch_all("SELECT * FROM setting")
    if len(exists_data) == 0:
        for item in setting_data:
            await db_manager.insert("setting", item)
